﻿using AduSkin.Controls;
using AduSkin.Controls.Metro;
using DBMC_Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace DBMC
{
    /// <summary>
    /// GameStarting.xaml 的交互逻辑
    /// </summary>
    public partial class GameStarting : Window
    {
        public ObservableCollection<UserInfo> Users { get; set; }

        public Minecraft minecraft = new Minecraft();
        public Danbai danbai = new Danbai();
        MicrosoftOAuth oauth = new MicrosoftOAuth();
        LauncherCore launcherCore = new LauncherCore();
        StartToTools startToTools = new StartToTools();
        private string GetJavaPathFromJson
        {
            get
            {
                string javaPath = string.Empty;

                if (launcherCore.ConfigFileExists)
                {
                    // 读取JSON文件的内容
                    string jsonData = File.ReadAllText(launcherCore.ConfigFile);

                    // 反序列化JSON内容到RootObject类的实例
                    RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);

                    // 获取JavaPath的值
                    if (dbmcData != null)
                    {
                        javaPath = dbmcData.JavaPath;
                    }
                }

                return javaPath;
            }
        }
        public static int Pid;
        public static string UseSaveTitle, UseSaveName, UseSavePath, ServerMotd, CurrentPlayerCount, MaxPlayerCount, Port, AveragePingTime;
        public static bool IsLinked = false;
        MinecraftServerConnection tcpClient = null;
        private string accessType(bool w = false)
        {
            if(w == false)
            {
                return "微软";
            }
            else
            {
                return "离线";
            }
        }

        public GameStarting(int memory, string name, string uuid, string accessToken, string refresh_token, bool main = false, bool msa = false, bool StartTools = true, bool GameTips = true)
        {
            InitializeComponent();
            Loaded += async (sender, e) =>
            {
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 窗口打开正常");
                //Console.WriteLine(memory);
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 加载玩家信息");
                LoadUsers();
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏启动参数：启动内存：{memory}，玩家名称：{name}，UUID：{uuid}，账号类型：{accessType(msa)}，造图小工具开关：{StartTools}，游戏提示工具开关：{GameTips}");
                await StartGame(memory, name, uuid, accessToken, refresh_token, main, msa, StartTools, GameTips);
            };
        }

        public void LoadUsers()
        {
            if (launcherCore.ConfigFileExists)
            {
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                if (dbmcData?.Account != null)
                {
                    Users = new ObservableCollection<UserInfo>(dbmcData.Account);
                }
            }
        }

        public void SaveUsers()
        {
            if (launcherCore.ConfigFileExists)
            {
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                // 确保 dbmcData.Account 也是 ObservableCollection<UserInfo> 类型
                dbmcData.Account = new ObservableCollection<UserInfo>(Users);
                string updatedJsonData = JsonConvert.SerializeObject(dbmcData, Formatting.Indented);
                File.WriteAllText(launcherCore.ConfigFile, updatedJsonData);
            }
        }

        private BitmapImage DecodeImageFromBase64(string base64String)
        {
            BitmapImage image = new BitmapImage();
            if (!string.IsNullOrEmpty(base64String))
            {
                byte[] imageBytes = Convert.FromBase64String(base64String);
                using (MemoryStream memStream = new MemoryStream(imageBytes))
                {
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = memStream;
                    image.EndInit();
                    image.Freeze(); // 因为是在非UI线程使用UI资源，所以进行冻结
                }
            }
            return image;
        }

        private void LoadHead(string name)
        {
            LauncherCore.WriteLog($"启动器核心：启动游戏 - 获取玩家头像中...");
            // 文件缓存目录
            string cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp", "DBMC", "MCImageCache");
            string cacheFile = Path.Combine(cacheDir, $"{name}.png");

            // 检查缓存是否存在且有效
            if (File.Exists(cacheFile) && (DateTime.Now - File.GetLastWriteTime(cacheFile)).TotalDays < 1)
            {
                // 从本地缓存加载图像
                BitmapImage image = new BitmapImage(new Uri(cacheFile));
                HeadSkin.Source = image;
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 已从缓存获取到玩家头像");
            }
            else
            {
                // 尝试从网络加载图像
                BitmapImage image = new BitmapImage();

                try
                {
                    image.BeginInit();
                    image.UriSource = new Uri("https://mineskin.eu/helm/" + $"{name}" + "/100.png", UriKind.Absolute);
                    image.CacheOption = BitmapCacheOption.OnLoad; // 设置缓存选项
                    image.DownloadCompleted += (s, e) =>
                    {
                        // 图像下载成功，保存到本地缓存
                         SaveImageToCacheAsync(image, cacheDir, cacheFile);
                    };
                    image.DownloadFailed += (s, e) =>
                    {
                        // 如果下载失败，使用默认的Base64编码的图像
                        image = DecodeImageFromBase64(Danbai.HandImage);
                        HeadSkin.Source = image;
                        LauncherCore.WriteLog($"启动器核心：启动游戏 - 获取玩家头像失败，已使用默认头像");
                    };
                    image.EndInit();
                    HeadSkin.Source = image;
                    LauncherCore.WriteLog($"启动器核心：启动游戏 - 已从网络获取到玩家头像");
                }
                catch
                {
                    // 如果在初始化图像期间发生异常，使用Base64默认图像
                    image = DecodeImageFromBase64(Danbai.HandImage);
                    HeadSkin.Source = image;
                    LauncherCore.WriteLog($"启动器核心：启动游戏 - 获取玩家头像失败，已使用默认头像");
                }
            }
        }

        // 保存图像到本地缓存
        private void SaveImageToCacheAsync(BitmapSource image, string cacheDir, string cacheFile)
        {
            if (!Directory.Exists(cacheDir))
            {
                Directory.CreateDirectory(cacheDir);
            }

            using (var fileStream = new FileStream(cacheFile, FileMode.Create))
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(fileStream);
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 玩家头像已缓存");
            }
        }

        public async Task StartGame(int memory, string name, string uuid, string accessToken, string refresh_token, bool main, bool msa, bool StartTools, bool GameTips)
        {
            LauncherCore.WriteLog($"启动器核心：启动游戏 - 准备启动游戏");
            CancellationTokenSource cancellationTokenSource = null;
            UserInfo existingUser = Users.FirstOrDefault(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
            string AccessToken = null;
            string JavaPath = minecraft.JavaCorePath;
            LauncherCore.WriteLog($"启动器核心：启动游戏 - 已获取到默认位置的Java");
            LoadHead(name);
            LauncherCore.WriteLog($"启动器核心：启动游戏 - 验证玩家信息中...");
            if (msa)
            {
                if (existingUser != null)
                {
                    if (launcherCore.HasMoreThan24HoursPassed(existingUser.Time))
                    {
                        LauncherCore.WriteLog($"启动器核心：启动游戏 - 账号信息刷新中...");
                        UpdateTips("账号信息已失效，刷新中...");
                        string Refresh_token = await oauth.RefreshToToken(refresh_token);
                        if (Refresh_token != null)
                        {
                            LauncherCore.WriteLog($"启动器核心：启动游戏 - 使用令牌刷新信息中...");
                            dynamic RefreshTokenRes = JsonConvert.DeserializeObject(Refresh_token);
                            string accesstoken = await RefreshMinecraftToken((string)RefreshTokenRes.access_token);
                            if (!string.IsNullOrEmpty(accesstoken))
                            {
                                AccessToken = accesstoken;
                                existingUser.Access_Token = accesstoken;
                                existingUser.Refresh_Token = (string)RefreshTokenRes.refresh_token;
                                existingUser.Type = "msa";
                                existingUser.Time = launcherCore.GenerateTimeStamp;
                                SaveUsers();
                                LauncherCore.WriteLog($"启动器核心：启动游戏 - 账号信息刷新成功");
                                UpdateTips("账号信息刷新成功");
                            }
                        }
                    }
                    else
                    {
                        AccessToken = accessToken;
                    }
                }
            }
            else
            {
                AccessToken = accessToken;
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 验证玩家信息完成");
            }
            UpdateTips("游戏启动中...");
            await Task.Delay(1000);
            minecraft.SetMaxMemory(memory);
            minecraft.InitCommand.Add($"-Dlog4j.configurationFile=\"{danbai.Log4j2}\"");
            minecraft.InitCommand.Add($"-Dminecraft.client.jar=\"{ danbai.Core}\"");
            minecraft.InitCommand.Add($"-Djava.library.path=\"{ danbai.Natives}\"");
            minecraft.InitCommand.Add($"-cp \"{minecraft.GetLibraries + danbai.Core}\"");
            minecraft.InitCommand.Add($@"net.minecraft.launchwrapper.Launch");
            minecraft.InitCommand.Add($@"--tweakClass cpw.mods.fml.common.launcher.FMLTweaker");
            minecraft.InitCommand.Add($@"--tweakClass com.mumfrey.liteloader.launch.LiteLoaderTweaker");
            minecraft.SetDanbaiUserInfo(name, uuid, AccessToken);

            await Task.Delay(1000);
            try
            {
                if (!minecraft.IsJava)
                {
                    LauncherCore.WriteLog($"启动器核心：启动游戏 - 未找到默认位置的Java，切换至系统位置的Java");
                    if (!minecraft.CheckJavaVersion)
                    {
                        LauncherCore.WriteLog($"启动器核心：启动游戏 - 未找到系统位置的Java，切换至自定义位置的Java");
                        if (GetJavaPathFromJson == "")
                        {
                            LauncherCore.WriteLog($"启动器核心：启动游戏 - 未找到Java");
                            UpdateTips("未找到Java，请安装或自定义选择 Java 后重试");
                            ThisClose(main);
                            return;
                        }
                        else
                        {
                            JavaPath = GetJavaPathFromJson;
                            LauncherCore.WriteLog($"启动器核心：启动游戏 - 切换自定义位置的 Java 成功");
                        }
                    }
                    else
                    {
                        JavaPath = "java.exe";
                        LauncherCore.WriteLog($"启动器核心：启动游戏 - 切换系统位置的 Java 成功");
                    }
                }
                await Task.Delay(1000);
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏启动中...");
                // 设置进程启动信息
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    WorkingDirectory = minecraft.GamePath,
                    FileName = JavaPath,
                    Arguments = minecraft.Command,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                // 启动进程，并获取输出
                using (Process process = new Process { StartInfo = psi })
                {
                    LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏启动成功");
                    bool isSuccess = false;
                    bool isSave = false;
                    string SaveName = null;
                    string UseSavePath, UseSaveName = null;
                    StringBuilder outputBuilder = new StringBuilder();
                    StringBuilder errorBuilder = new StringBuilder();

                    Regex Loading = new Regex(@"Loading tweak class name cpw.mods.fml.common.launcher.FMLTweaker");
                    Regex Loaded = new Regex(@"Injecting ons40packetdisconnect\[x1\] in func_148833_a in S40PacketDisconnect");
                    Regex localJoinSave = new Regex(@"Preparing start region for level 0");
                    Regex localExitSave = new Regex(@"Stopping server");
                    Regex ClientConnectingServerCouldnConnect = new Regex(@"Couldn't connect to server");
                    Regex ClientConnectingServerEstablishedConnect = new Regex(@"Client side modded connection established");
                    Regex ServerConnectingServerEstablishedConnect = new Regex(@"Server side modded connection established");
                    Regex SaveLoading = new Regex(@"Mw\.load: loading\.\.\.");
                    Regex SaveClosing = new Regex(@"Mw\.close: closing\.\.\.");
                    Regex SaveSaving = new Regex(@"Saving and pausing game\.\.\.");
                    Regex Exit = new Regex(@"Stopping!");

                    process.OutputDataReceived += async (sender, e) =>
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            outputBuilder.AppendLine(e.Data);
                            //Console.WriteLine(e.Data);
                            LauncherCore.WriteGameLog(e.Data);

                            if (SaveName == null)
                            {
                                SaveName = GetSaveName(e.Data);
                            }

                            if (Loading.IsMatch(e.Data))
                            {
                                LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏正在加载");
                                UpdateTips("游戏加载中...");
                                if (StartTools)
                                {
                                    await Task.Delay(20000);
                                    await Dispatcher.InvokeAsync(() =>
                                    {
                                        startToTools.Show();
                                    });
                                }
                            }
                            else if (Loaded.IsMatch(e.Data))
                            {
                                LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏加载完成");
                                UpdateTips("游戏加载完毕");
                                await Task.Delay(1000);
                                await Dispatcher.InvokeAsync(() =>
                                {
                                    WindowState = WindowState.Minimized;
                                });
                                if (StartTools)
                                {
                                    await Task.Delay(1000);
                                    await Dispatcher.InvokeAsync(() =>
                                    {
                                        Close();
                                        startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.OpenInApp);
                                        startToTools.UpdateMainLoadingTips("等待用户操作...");
                                    });
                                }
                            }
                            else if (Exit.IsMatch(e.Data))
                            {
                                //Console.WriteLine("游戏主动关闭");
                                if (StartTools)
                                {
                                    await Dispatcher.InvokeAsync(() =>
                                    {
                                        if (LauncherTools.NBTExplorer.Close())
                                        {
                                            startToTools.Close();
                                        }
                                        else
                                        {
                                            startToTools.Close();
                                        }
                                    });
                                }
                            }
                            else if (localJoinSave.IsMatch(e.Data))
                            {
                                //Console.WriteLine("存档加载");
                                isSave = true;
                            }
                            else if (localExitSave.IsMatch(e.Data))
                            {
                                //Console.WriteLine("存档关闭");
                            }

                            if (isSave)
                            {
                                if (SaveLoading.IsMatch(e.Data))
                                {
                                    if (GameTips)
                                    {
                                        Notification("单人游戏", SaveName, "加载");
                                    }
                                    if (StartTools)
                                    {
                                        await Task.Delay(300);
                                        List<SavePath> savePaths = LauncherTools.TraverseDirectories(minecraft.SavesPath);
                                        if (savePaths.Count > 0)
                                        {
                                            foreach (SavePath savePath in savePaths)
                                            {
                                                if (savePath.Locked)
                                                {
                                                    UseSaveName = savePath.Name;
                                                    UseSavePath = savePath.Path;
                                                    await Dispatcher.InvokeAsync(() =>
                                                    {
                                                        startToTools.Title = $"造图小助手 - {SaveName}/{savePath.Name}";
                                                        startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.FolderOpen);
                                                        startToTools.UpdateMainLoadingTips($"{SaveName}/{savePath.Name} - 等待存档加载...");
                                                    });
                                                    await Task.Delay(2000);
                                                    Dispatcher.Invoke(() =>
                                                    {
                                                        startToTools.UpdateMainLoadingTips("存档加载完毕");
                                                        startToTools.UpdateSaveInfo(SaveName, savePath.Name, savePath.Path);
                                                        startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.Hidden);
                                                        startToTools.SaveInfoVisibleVisible();
                                                    });
                                                }
                                            }
                                        }
                                    }
                                    //Console.WriteLine("当前存档已加载");
                                }
                                string LocalAreaNetworkPort = GetLocalAreaNetworkPort(e.Data);
                                if (LocalAreaNetworkPort != null)
                                {
                                    if (StartTools)
                                    {
                                        cancellationTokenSource = new CancellationTokenSource();
                                        MonitorServerInfo("127.0.0.1", int.Parse(LocalAreaNetworkPort), cancellationTokenSource.Token, isSave);
                                        if (GameTips)
                                        {
                                            Notification($"局域网游戏，{LocalAreaNetworkPort}端口开放", SaveName, "小助手已连接", EnumPromptType.Success);
                                        }
                                    }
                                }
                                Command_Tp Command_Tp = GetHostMachineCommand_Tp(e.Data);
                                if (Command_Tp != null)
                                {
                                    if (GameTips)
                                    {
                                        if (Command_Tp.PlayerName2 != null)
                                        {
                                            await Dispatcher.InvokeAsync(() =>
                                            {
                                                NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                                                {
                                                    Title = "游戏进程",
                                                    Content = $"执行人：{Command_Tp.UsePlayerName}\n事件：将 {Command_Tp.PlayerName} 传送至 {Command_Tp.PlayerName2} ",
                                                    NotificationType = EnumPromptType.Info
                                                });
                                            });
                                        }
                                        else
                                        {
                                            await Dispatcher.InvokeAsync(() =>
                                            {
                                                NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                                                {
                                                    Title = "游戏进程",
                                                    Content = $"执行人：{Command_Tp.UsePlayerName}\n事件：传送到坐标：{Command_Tp.X},{Command_Tp.Y},{Command_Tp.Z} ",
                                                    NotificationType = EnumPromptType.Info
                                                });
                                            });
                                        }
                                    }
                                }
                                if (SaveSaving.IsMatch(e.Data))
                                {
                                    if (GameTips)
                                    {
                                        Notification("单人游戏", SaveName, "自动保存");
                                    }
                                    //Console.WriteLine("当前存档已保存");
                                }
                                if (SaveClosing.IsMatch(e.Data))
                                {
                                    if (GameTips)
                                    {
                                        Notification("单人游戏", SaveName, "关闭");
                                    }

                                    if (StartTools)
                                    {
                                        await Dispatcher.InvokeAsync(() =>
                                        {
                                            startToTools.Title = $"造图小助手";
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.Visible);
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.OpenInApp);
                                            startToTools.UpdateMainLoadingTips("等待用户操作...");
                                            startToTools.SaveInfoVisibleCollapsed();
                                        });
                                        // 当你需要停止监控时
                                        if (cancellationTokenSource != null)
                                        {
                                            cancellationTokenSource.Cancel();
                                        }
                                    }
                                    SaveName = null;
                                    isSave = false;
                                    //Console.WriteLine("当前存档已关闭");
                                }
                            }
                            else
                            {
                                IPAndPort res = GetIPAndPort(e.Data);
                                if (res != null)
                                {
                                    if (StartTools)
                                    {
                                        cancellationTokenSource = new CancellationTokenSource();
                                        MonitorServerInfo(res.IP, res.Port, cancellationTokenSource.Token, isSave);
                                        await Dispatcher.InvokeAsync(() =>
                                        {
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.VectorLink);
                                            startToTools.UpdateMainLoadingTips($"等待游戏连接服务器...");
                                        });
                                    }
                                }

                                if (!ClientConnectingServerCouldnConnect.IsMatch(e.Data))
                                {
                                    if (SaveLoading.IsMatch(e.Data))
                                    {
                                        //Console.WriteLine("连接成功");
                                        if (StartTools)
                                        {
                                            if (GameTips)
                                            {
                                                Notification("多人游戏", ServerMotd, "小助手已连接", EnumPromptType.Success);
                                            }
                                            await Dispatcher.InvokeAsync(() =>
                                            {
                                                startToTools.Title = $"造图小助手 - {ServerMotd}";
                                                startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.Hidden);
                                            });
                                        }
                                    }
                                }
                                else
                                {
                                    //Console.WriteLine("连接失败");
                                    if (GameTips)
                                    {
                                        Notification("多人游戏", "", "小助手连接失败", EnumPromptType.Error);
                                    }
                                    if (StartTools)
                                    {
                                        await Task.Delay(1000);
                                        await Dispatcher.InvokeAsync(() =>
                                        {
                                            startToTools.Title = $"造图小助手";
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.Visible);
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.OpenInApp);
                                            startToTools.UpdateMainLoadingTips("等待用户操作...");
                                        });
                                    }
                                }
                                Command_Tp Command_Tp = GetHostMachineCommand_Tp(e.Data);
                                if (Command_Tp != null)
                                {
                                    if (GameTips)
                                    {
                                        if (Command_Tp.PlayerName2 != null)
                                        {
                                            await Dispatcher.InvokeAsync(() =>
                                            {
                                                NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                                                {
                                                    Title = "游戏进程",
                                                    Content = $"执行人：{Command_Tp.UsePlayerName}\n事件：将 {Command_Tp.PlayerName} 传送至 {Command_Tp.PlayerName2} ",
                                                    NotificationType = EnumPromptType.Info
                                                });
                                            });
                                        }
                                        else
                                        {
                                            await Dispatcher.InvokeAsync(() =>
                                            {
                                                NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                                                {
                                                    Title = "游戏进程",
                                                    Content = $"执行人：{Command_Tp.UsePlayerName}\n事件：传送到坐标：{Command_Tp.X},{Command_Tp.Y},{Command_Tp.Z} ",
                                                    NotificationType = EnumPromptType.Info
                                                });
                                            });
                                        }
                                    }

                                }
                                if (SaveClosing.IsMatch(e.Data))
                                {
                                    if (StartTools)
                                    {
                                        if (cancellationTokenSource != null)
                                        {
                                            cancellationTokenSource.Cancel();
                                        }
                                        await Dispatcher.InvokeAsync(() =>
                                        {
                                            startToTools.Title = $"造图小助手";
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.Visible);
                                            startToTools.UpdateMainLoadingStats(UpdateMainLoadingStatsType.OpenInApp);
                                            startToTools.UpdateMainLoadingTips("等待用户操作...");
                                        });
                                    }
                                    //Console.WriteLine("连接已关闭");
                                }
                            }
                        }
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            //UpdateTips(e.Data);
                            //Debug.WriteLine(e.Data);
                            errorBuilder.AppendLine(e.Data);
                        }
                    };

                    process.Start();
                    Dispatcher.Invoke(() =>
                    {
                        Pid = process.Id;
                    });
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();


                    while (!process.HasExited && !isSuccess)
                    {
                        await Task.Delay(100);
                    }

                    process.WaitForExit();

                    // 检查进程退出代码
                    if (process.ExitCode != 0)
                    {
                        uint exitCode = unchecked((uint)process.ExitCode);
                        if (exitCode == 3489660927)
                        {
                            LauncherCore.WriteLog($"启动器核心：启动游戏 - 启动游戏失败，原因可能是内存不足");
                            UpdateTips("游戏异常退出，可能是内存不足");
                            if (StartTools)
                            {
                                await Dispatcher.InvokeAsync(() =>
                                {
                                    if (LauncherTools.NBTExplorer.Close())
                                    {
                                        startToTools.Close();
                                    }
                                    else
                                    {
                                        startToTools.Close();
                                    }
                                });
                            }
                            ThisClose(main);
                        }
                        else
                        {
                            LauncherCore.WriteLog($"启动器核心：启动游戏 - 启动游戏失败，错误码：{exitCode}");
                            UpdateTips("游戏异常退出，Code：" + exitCode.ToString());
                            if (StartTools)
                            {
                                await Dispatcher.InvokeAsync(() =>
                                {
                                    if (LauncherTools.NBTExplorer.Close())
                                    {
                                        startToTools.Close();
                                    }
                                    else
                                    {
                                        startToTools.Close();
                                    }
                                });
                            }
                            ThisClose(main);
                        }
                    }
                    else
                    {
                        if (StartTools)
                        {
                            await Dispatcher.InvokeAsync(() =>
                            {
                                if (LauncherTools.NBTExplorer.Close())
                                {
                                    startToTools.Close();
                                }
                                else
                                {
                                    startToTools.Close();
                                }
                            });
                        }
                        LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏正常退出");
                        ThisClose(main);
                    }
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
                LauncherCore.WriteLog($"启动器核心：启动游戏 - 游戏启动失败，原因{ex.Message}");
                UpdateTips("启动失败");
                if (StartTools)
                {
                    await Dispatcher.InvokeAsync(() =>
                    {
                        if (LauncherTools.NBTExplorer.Close())
                        {
                            startToTools.Close();
                        }
                        else
                        {
                            startToTools.Close();
                        }
                    });
                }
                ThisClose(main);
            }
        }

        private async Task<string> RefreshMinecraftToken(string xboxtoken)
        {
            string XboxToken = await oauth.GetXboxToken(xboxtoken);
            if (XboxToken != null)
            {
                dynamic XboxTokenRes = JsonConvert.DeserializeObject(XboxToken);
                if (XboxTokenRes.Token != null)
                {
                    Console.WriteLine("XboxToken");
                    string Xsts = await oauth.GetXsts((string)XboxTokenRes.Token);
                    if (Xsts != null)
                    {
                        Console.WriteLine("Xsts");
                        JObject jsonResponse = JObject.Parse(Xsts);
                        string token = jsonResponse["Token"].ToString();
                        string uhs = jsonResponse["DisplayClaims"]["xui"][0]["uhs"].ToString();
                        if (uhs != null && token != null)
                        {
                            string MinecraftToken = await oauth.GetMinecraftToken(uhs, token);
                            if (MinecraftToken != null)
                            {
                                Console.WriteLine("MinecraftToken");
                                dynamic MinecraftTokenRes = JsonConvert.DeserializeObject(MinecraftToken);
                                if (MinecraftTokenRes.access_token != null)
                                {
                                    return (string)MinecraftTokenRes.access_token;
                                }
                            }
                        }
                    }
                }

            }
            return null;
        }

        private void Notification(string type, string SaveName, string message, EnumPromptType NotificationType = EnumPromptType.Info, bool multiplayer = false)
        {
            Dispatcher.Invoke(() =>
            {
                if (multiplayer)
                {
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "游戏进程",
                        Content = $"类型：{type}\n名称：{SaveName}\n事件：{message}",
                        NotificationType = NotificationType
                    });
                }
                else
                {
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "游戏进程",
                        Content = $"类型：{type}\n地图名称：{SaveName}\n事件：{message}",
                        NotificationType = NotificationType
                    });
                }

            });
        }

        private string GetSaveName(string input)
        {
            string pattern = @"Loading dimension 0 \(([^)]*)\)";

            Match match = Regex.Match(input, pattern);
            if (match.Success)
            {
                return match.Groups[1].Value;
            }
            else
            {
                return null;
            }
        }

        private Command_Tp GetHostMachineCommand_Tp(string input)
        {
            string pattern = @"\[([^\[]*?): 将 (.*?) 传送到 ([\d.-]+)，([\d.-]+)，([\d.-]+)\]";
            string pattern2 = @"\[([^\[]*?): 已将 (.*?) 传送至 (.*?)\]";

            Match match = Regex.Match(input, pattern);
            Match match2 = Regex.Match(input, pattern2);

            if (match2.Success)
            {
                return new Command_Tp
                {
                    UsePlayerName = match2.Groups[1].Value.Replace("[", ""),
                    PlayerName = match2.Groups[2].Value,
                    PlayerName2 = match2.Groups[3].Value.Replace("]", "")
                };
            }
            if (match.Success)
            {
                int x = (int)Math.Floor(double.Parse(match.Groups[3].Value));
                int y = (int)Math.Floor(double.Parse(match.Groups[4].Value));
                int z = (int)Math.Floor(double.Parse(match.Groups[5].Value));

                return new Command_Tp
                {
                    UsePlayerName = match.Groups[1].Value.Replace("[", ""),
                    PlayerName = match.Groups[2].Value,
                    X = x,
                    Y = y,
                    Z = z
                };
            }
            return null;
        }

        private string GetLocalAreaNetworkPort(string input)
        {
            string pattern = @"Started on ([\d.-]+)";
            Match match = Regex.Match(input, pattern);
            if (match.Success)
            {
                return match.Groups[1].Value;
            }
            return null;
        }

        private Command_Tp GetClientMachineCommand_Tp(string input)
        {
            string pattern = @"\[CHAT\] 将 (.*?) 传送到 ([-\d.]+)，([-\d.]+)，([-\d.]+)";
            string pattern2 = @"\[CHAT\] 已将 (.*?) 传送至 (.*?)";

            Match match = Regex.Match(input, pattern);
            Match match2 = Regex.Match(input, pattern2);

            if (match2.Success)
            {
                return new Command_Tp
                {
                    PlayerName = match2.Groups[1].Value,
                    PlayerName2 = match2.Groups[2].Value
                };
            }
            if (match.Success)
            {
                string userName = match.Groups[1].Value;
                int x = (int)Math.Floor(double.Parse(match.Groups[2].Value));
                int y = (int)Math.Floor(double.Parse(match.Groups[3].Value));
                int z = (int)Math.Floor(double.Parse(match.Groups[4].Value));

                return new Command_Tp
                {
                    PlayerName = userName,
                    X = x,
                    Y = y,
                    Z = z
                };
            }
            return null;
        }

        private Command_Setworldspawn GetHostMachineCommand_Setworldspawn(string input)
        {
            string pattern = @"\[(.*?): 已将世界出生点设置为（(\d+)，(\d+)，(-\d+)）\]";

            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                string username = match.Groups[1].Value.Replace("[", "");
                int x = int.Parse(match.Groups[2].Value);
                int y = int.Parse(match.Groups[3].Value);
                int z = int.Parse(match.Groups[4].Value);

                return new Command_Setworldspawn
                {
                    UsePlayerName = username,
                    X = x,
                    Y = y,
                    Z = z
                };
            }
            return null;
        }

        private Command_Setworldspawn GetClientMachineCommand_Setworldspawn(string input)
        {
            string pattern = @"\[CHAT\] 将(.*?)的出生点设置到\((-?\d+)，(-?\d+)，(-?\d+)\)";

            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                string username = match.Groups[1].Value;
                int x = int.Parse(match.Groups[2].Value);
                int y = int.Parse(match.Groups[3].Value);
                int z = int.Parse(match.Groups[4].Value);

                return new Command_Setworldspawn
                {
                    UsePlayerName = username,
                    X = x,
                    Y = y,
                    Z = z
                };
            }
            return null;
        }

        private Command_Spawnpoint GetHostMachineCommand_Spawnpoint(string input)
        {
            string pattern = @"\[(.*?): 将(.*?)的出生点设置到\((\d+)，(\d+)，(-?\d+)\)\]";

            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                return new Command_Spawnpoint
                {
                    UsePlayerName = match.Groups[1].Value.Replace("[", ""),
                    PlayerName = match.Groups[2].Value,
                    X = int.Parse(match.Groups[3].Value),
                    Y = int.Parse(match.Groups[4].Value),
                    Z = int.Parse(match.Groups[5].Value)
                };
            }
            return null;
        }

        private Command_Spawnpoint GetClientMachineCommand_Spawnpoint(string input)
        {
            string pattern = @"\[CHAT\] 将(.*?)的出生点设置到\((\d+)，(\d+)，(-?\d+)\)";

            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                return new Command_Spawnpoint
                {
                    PlayerName = match.Groups[1].Value,
                    X = int.Parse(match.Groups[2].Value),
                    Y = int.Parse(match.Groups[3].Value),
                    Z = int.Parse(match.Groups[4].Value)
                };
            }
            return null;
        }

        private IPAndPort GetIPAndPort(string input)
        {
            string pattern = @"Connecting to (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}),\s*(\d+)";
            Match match = Regex.Match(input, pattern);

            if (match.Success)
            {
                return new IPAndPort
                {
                    IP = match.Groups[1].Value,
                    Port = int.Parse(match.Groups[2].Value)
                };
            }
            return null;
        }

        private async void MonitorServerInfo(string ServeIp, int ServePort, CancellationToken cancellationToken, bool LocalAreaNetwork = false)
        {
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    using (MinecraftServerConnection connection = ServerInfo(ServeIp, ServePort, LocalAreaNetwork))
                    {
                        IPAddress ip = IPAddress.Parse(ServeIp);
                        long averagePingTime = GetAveragePingTime(ip);
                        if (connection != null)
                        {
                            tcpClient = connection;
                            ServerMotd = connection.ServerInfo.ServerMotd.ToString();
                            CurrentPlayerCount = connection.ServerInfo.CurrentPlayerCount.ToString();
                            MaxPlayerCount = connection.ServerInfo.MaxPlayerCount.ToString();
                            AveragePingTime = averagePingTime.ToString() + "ms";
                            if (LocalAreaNetwork)
                            {
                                //Notification($"局域网游戏，{ServePort}端口开放", connection.ServerInfo.ServerMotd, "小助手已连接", EnumPromptType.Success);
                                await Dispatcher.InvokeAsync(() =>
                                {
                                    startToTools.UpdateLocalAreaNetworkGameInfo(connection.ServerInfo.MaxPlayerCount.ToString(), connection.ServerInfo.CurrentPlayerCount.ToString(), ServePort.ToString());
                                    startToTools.LocalAreaNetworkGameInfoVisible();
                                });
                            }
                            else
                            {
                                //Notification("多人游戏", connection.ServerInfo.ServerMotd, "小助手已连接", EnumPromptType.Success);
                                await Dispatcher.InvokeAsync(() =>
                                {
                                    startToTools.UpdateMultiplayerGameInfo(connection.ServerInfo.ServerMotd.ToString(), connection.ServerInfo.MaxPlayerCount.ToString(), connection.ServerInfo.CurrentPlayerCount.ToString(), $"{ServeIp}:{ServePort}", averagePingTime.ToString() + "ms");
                                    startToTools.MultiplayerGameInfoVisible();
                                });
                            }

                        }
                        await Task.Delay(5000, cancellationToken).ConfigureAwait(false); // 增加延迟时间，降低更新频率
                    }
                }
            }
            catch (TaskCanceledException)
            {
                if (CloseConnection(tcpClient, LocalAreaNetwork))
                {
                    tcpClient = null;
                    ServerMotd = null;
                    CurrentPlayerCount = null;
                    MaxPlayerCount = null;
                    AveragePingTime = null;
                }
            }
            // 捕获其他可能的异常
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

        }

        private MinecraftServerConnection ServerInfo(string ServeIp, int ServePort, bool LocalAreaNetwork = false)
        {
            MinecraftServerConnection connection = null;
            try
            {
                IPAddress ip = IPAddress.Parse(ServeIp);
                int serverPort = ServePort;

                // 创建连接对象
                connection = new MinecraftServerConnection(ip, serverPort);

                return connection;
            }
            catch (Exception)
            {
                if (connection != null)
                {
                    if (LocalAreaNetwork)
                    {
                        Notification("局域网游戏", connection.ServerInfo.ServerMotd, "小助手连接失败", EnumPromptType.Error);
                        startToTools.LocalAreaNetworkGameInfoCollapsed();
                    }
                    else
                    {
                        Notification("多人游戏", connection.ServerInfo.ServerMotd, "小助手连接失败", EnumPromptType.Error);
                        startToTools.MultiplayerGameInfoCollapsed();
                    }
                }
                return null;
            }
        }

        private long GetAveragePingTime(IPAddress ip)
        {
            var pingSender = new Ping();
            long totalPingTime = 0;
            int successfulPings = 0;
            for (int i = 0; i < 5; i++)
            {
                var reply = pingSender.Send(ip, 1000);
                if (reply.Status == IPStatus.Success)
                {
                    totalPingTime += reply.RoundtripTime;
                    successfulPings++;
                }
            }
            return successfulPings > 0 ? totalPingTime / successfulPings : -1;
        }

        private bool CloseConnection(MinecraftServerConnection tcpClient, bool LocalAreaNetwork = false)
        {
            if (tcpClient != null)
            {
                tcpClient.Dispose();
                if (LocalAreaNetwork)
                {
                    Notification("局域网游戏", tcpClient.ServerInfo.ServerMotd, "小助手已断开", EnumPromptType.Success);
                    Dispatcher.Invoke(() =>
                    {
                        startToTools.LocalAreaNetworkGameInfoCollapsed();
                    });
                    return true;
                }
                else
                {
                    Notification("多人游戏", tcpClient.ServerInfo.ServerMotd, "小助手已断开", EnumPromptType.Success);
                    Dispatcher.Invoke(() =>
                    {
                        startToTools.MultiplayerGameInfoCollapsed();
                    });
                    return true;
                }
            }
            return false;
        }

        public void UpdateTips(string text)
        {
            // 使用Dispatcher确保更新UI的操作在UI线程中进行
            Dispatcher.Invoke(() => { Tips.Text = text; });
        }

        private void OpenMainWindow()
        {
            // 使用 Dispatcher 确保在 UI 线程中打开新窗口
            Dispatcher.Invoke(() =>
            {
                MainWindow mainWindow = new MainWindow();
                mainWindow.Show();
                mainWindow.Topmost = true;  // 将窗口暂时设置为最前
                mainWindow.Topmost = false; // 然后立即取消最前设置
            });
        }

        private void ThisClose(bool main)
        {
            // 使用 Dispatcher 确保在 UI 线程中打开新窗口
            Dispatcher.Invoke(async () =>
            {
                await Task.Delay(1000);
                if (main)
                {
                    OpenMainWindow();
                    Close();
                }
                else
                {
                    Application.Current.Shutdown();
                }
            });
        }
    }
}

class IPAndPort
{
    public string IP { get; set; }
    public int Port { get; set; }
}

public class Command_Tp
{
    public string UsePlayerName { get; set; }
    public string PlayerName { get; set; }
    public string PlayerName2 { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}

public class Command_Setworldspawn
{
    public string UsePlayerName { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}

public class Command_Spawnpoint
{
    public string UsePlayerName { get; set; }
    public string PlayerName { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}